/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.security.tapestry.services.impl;

import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.BaseURLSource;
import org.apache.tapestry5.services.Request;
import org.libermundi.theorcs.core.tapestry.services.configuration.ApplicationConfig;
import org.libermundi.theorcs.security.SecurityConstants;

/**
 * @author Martin Papy
 *
 */
public class OrcsUrlSourceImpl implements BaseURLSource {
    private final Request _request;
    
    private String _hostname;
    private int _hostPort;
    private int _secureHostPort;
    private boolean _isSSLEnabled;
    
	public OrcsUrlSourceImpl(Request request, ApplicationConfig appConfig, @Inject @Symbol(SymbolConstants.HOSTNAME) String hostname,
		    @Symbol(SymbolConstants.HOSTPORT) int hostPort) {
	        this._request = request;
	        this._hostname = hostname;
	        this._hostPort = hostPort;
	        this._secureHostPort = appConfig.getInteger(SecurityConstants.SSL_PORT);
	        this._isSSLEnabled = appConfig.getBoolean(SecurityConstants.SSL_ENABLED);
	}	

	/* (non-Javadoc)
	 * @see org.apache.tapestry5.services.BaseURLSource#getBaseURL(boolean)
	 */
	@Override
	public String getBaseURL(boolean secure) {
        int port = secure ? _secureHostPort : _hostPort;
        String portSuffix = "";

        if (port <= 0) { 
            port = _request.getServerPort();
            int schemeDefaultPort = _request.isSecure() ? 443 : 80;
            portSuffix = port == schemeDefaultPort ? "" : ":" + port;
        }
        else if (secure && port != 443) portSuffix = ":" + port;
        else if (port != 80) portSuffix = ":" + port;
        
        String hostname = "".equals(this._hostname) ? _request.getServerName() : _hostname.startsWith("$") ? System.getenv(_hostname.substring(1)) : this._hostname;
        
        return String.format("%s://%s%s", (secure && _isSSLEnabled) ? "https" : "http", hostname, portSuffix);		
	}

}
